﻿using System;
using System.Threading;
using SharpDX.DirectInput;
namespace TableTool;
public class ReadDex
{
    public Action<Key> KeyOut;
    public void Read()
    {
        // 初始化DirectInput
        DirectInput directInput = new DirectInput();

        // 创建一个用于监听键盘的设备
        Keyboard keyboard = new Keyboard(directInput);
        keyboard.SetCooperativeLevel(IntPtr.Zero, 
            CooperativeLevel.Background | CooperativeLevel.NonExclusive);

        // 尝试获取键盘的状态
        try
        {
            keyboard.Acquire();
          
        }
        catch (Exception ex)
        {
            Console.WriteLine($"无法获取键盘控制权: {ex.Message}");
            return;
        }

        // 读取键盘输入
        while (true)
        {
            KeyboardState state = keyboard.GetCurrentState();
            if (state == null || state.PressedKeys.Count == 0)
            {
                Thread.Sleep(100); // 如果没有按键按下，等待一会儿
                continue;
            }

            // 遍历按下的所有键
            foreach (Key key in state.PressedKeys)
            {
                KeyOut?.Invoke(key);
                Console.WriteLine($"DirectInput按下的键: {key}");
            }

            Thread.Sleep(100); // 控制循环频率，避免过于频繁的检测
        }
    }
}
